package member

import (
	"github.com/yl10/kit/guid"
	"lao-a/helper"
	"lao-a/models/model"
	"time"
)

const (
	STATUS_NORMAL = iota + 1
)

// InitAccount 初始化用户及会员卡
func (m *DAO) InitAccount(cardNum, memId, memType string) (*model.TaCardAccount, error) {
	if cardNum == "" {
		return nil, helper.LogError("初始化会员账户失败, 会员卡号为空")
	}
	if memId == "" {
		return nil, helper.LogError("初始化会员账户失败, 会员ID为空")
	}
	if memType == "" {
		return nil, helper.LogError("初始化会员账户失败, 会员类型为空")
	}

	lvls, e1 := m.GetMemberNormalLvl()
	if e1 != nil {
		return nil, e1
	}

	user := m.ctx.User.(*model.SysUser)
	now := time.Now()

	acc := &model.TaCardAccount{
		AccId: guid.NewGUIDString(),
		CardNum: cardNum,
		MemId:   memId,
		MemType: memType,
		Points: 0,
		LevelId: lvls[0].LevelId,
		Liveness: 0,
		CashLeft: "0.0",
		CashPay: "0.0",
		ModifyUser: user.UserId,
		ModifyDate: now,
	}

	_, err := m.db.Insert(acc)
	if err != nil {
		return nil, helper.LogError("初始化会员账户失败", err)
	}

	return acc, nil
}

//
func (m *DAO) UpdateAccount(accId string, newData map[string]interface{}) error {
	var acc model.TaCardAccount
	var cols []string

	for k, v := range newData {
		switch k {
			case "Points":
				cols = append(cols, "points")
				acc.Points = v.(int)
			case "LevelId":
				cols = append(cols, "level_id")
				acc.LevelId = v.(int)
			case "Liveness":
				cols = append(cols, "liveness")
				acc.Liveness = v.(int)
			case "CashLeft":
				cols = append(cols, "cash_left")
				acc.CashLeft = v.(string)
			case "CashPay":
				cols = append(cols, "cash_pay")
				acc.CashPay = v.(string)
			default:
		}
	}

	if len(cols) == 0 {
		return nil
	}

	user := m.ctx.User.(*model.SysUser)
	now := time.Now()
	acc.ModifyUser = user.UserId
	acc.ModifyDate = now
	cols = append(cols, "modify_user")
	cols = append(cols, "modify_date")

	if _, err := m.db.Update(&acc, cols, "acc_id=?", accId); err != nil {
		return helper.LogError("更新会员账户失败", err)
	}

	return nil
}

// GetPointsList 获取积分列表
func (m *DAO) GetPointsList(accId string) ([]model.TaDetailPoints, error) {
	var list []model.TaDetailPoints

	if err := m.db.Where("acc_id=?", accId).
		And("status=?", STATUS_NORMAL).
		Desc("create_date").Find(&list);
		err != nil {
			return nil, helper.LogError("获取积分流水失败", err)
	}

	return list, nil;
}

// GetCashList 获取现金流水失败
func (m *DAO) GetCashList(accId string) ([]model.TaCashItems, error) {
	var list []model.TaCashItems

	if err := m.db.Where("acc_id=?", accId).
		And("status=?", STATUS_NORMAL).
		Desc("create_date").Find(&list);
		err != nil {
			return nil, helper.LogError("获取现金流水失败", err)
	}

	return list, nil;
}

// GetLivenessList 获取活跃度流水
func (m *DAO) GetLivenessList(accId string) ([]model.TaLivenessItems, error) {
	var list []model.TaLivenessItems

	if err := m.db.Where("acc_id=?", accId).
		And("status=?", STATUS_NORMAL).
		Desc("create_date").Find(&list);
		err != nil {
			return nil, helper.LogError("获取活跃度流水失败", err)
	}

	return list, nil;
}
